// import 'package:common_lib/common_compoent.dart';
import 'dart:convert';

import 'package:common_lib/common_compoent.dart';
import 'package:common_lib/patient_management/patient_list/patient_list_entity.dart'
    as PatientBean;
import 'package:doctor_examine_lib/doctor_examine_componet.dart';
import 'package:doctor_examine_lib/doctor_examine_lib.dart';
import 'package:doctor_examine_lib/examine_list/examine_list_entity.dart'
    as ExamineBean;
import 'package:doctor_examine_lib/hospital_list/hospital_list_entity.dart'
    as HospitalBean;
import 'package:doctor_examine_lib/repository/https.dart';
import 'package:doctor_login_lib/cache/userinfo_cache.dart';
import 'package:doctor_login_lib/login/entity/doctor_login_entity.dart'
    as DoctorBean;
import 'package:flutter/cupertino.dart';
import 'package:base_lib/common/bloc/base_bloc.dart';
import 'package:base_lib/index.dart';
import 'package:rxdart/rxdart.dart';

class OffineExamineBloc extends BaseBloc {
  DoctorBean.DoctorUser _userInfo;
  PatientBean.Datum _patientInfo = PatientBean.Datum();
  HospitalBean.Datum _hospitalInfo = HospitalBean.Datum();
  List<ExamineBean.SubDatum> _examineItems = List<ExamineBean.SubDatum>();
  BehaviorSubject<PatientBean.Datum> patientInfoSubject = BehaviorSubject();
  BehaviorSubject<HospitalBean.Datum> hospitalInfoSubject = BehaviorSubject();
  BehaviorSubject<List<ExamineBean.SubDatum>> examineItemsSubject =
      BehaviorSubject();
  String _tentativeDiagnosis = "";
  String _note = "";
  var patientEventHandler;

  @override
  void initState() async {
    super.initState();
    _userInfo = await UserInfoCache.getInstance().get();
    patientEventHandler = (context, parameters) {
      _patientInfo = parameters.getObj('patientInfo');
      FLog(json.encode(_patientInfo));
      patientInfoSubject?.add(_patientInfo);
      return;
    };
    // 注册添加就诊人bus
    EventBus.instance
        .register(CommonBusName.selectedPatient, patientEventHandler);
  }

  // 操作-初步诊断
  void editTentativeDiagnosis(value) {
    _tentativeDiagnosis = value;
  }

  // 操作-备注
  void editNote(value) {
    _note = value;
  }

  // 操作-添加就诊人
  void jumpToPatientListPage(BuildContext context) {
    DoctorExamineLib.jumpPatientManagement(context);
  }

  // 操作-选择检查医院
  void selectExamineHospital(BuildContext context) {
    Routers.navigateTo(context, DoctorExamineComponent.hospitalListPage)
        .then((parameters) {
      _hospitalInfo = parameters.getObj('hospitalInfo');
      hospitalInfoSubject.add(_hospitalInfo);
    });
  }

  // 操作-选择检查项目
  void addExamineItem(BuildContext context) {
    if (ObjectUtil.isEmpty(_hospitalInfo.orgId)) {
      ToastUtil.warning("请先选择检查医院");
      return;
    }
    Routers.navigateTo(context, DoctorExamineComponent.examineListPage,
            parameters: Parameters()
              ..putString("hospitalID", _hospitalInfo.orgId))
        .then((parameters) {
      _examineItems.add(parameters.getObj("examineItem"));
      FLog("msg-----ddd-----" + json.encode(_examineItems));
      examineItemsSubject.add(_examineItems);
    });
  }

  // 操作--添加线下就诊
  void addOfflineExamine() {
    if (ObjectUtil.isEmpty(_patientInfo.keyId)) {
      ToastUtil.info("请添加就诊人");
      return;
    }
    if (ObjectUtil.isEmpty(_tentativeDiagnosis)) {
      ToastUtil.info("请填写初步诊断信息");
      return;
    }
  }

  @override
  void dispose() {
    patientInfoSubject?.close();
    examineItemsSubject?.close();
    // 注销bus
    EventBus.instance
        .unregister(CommonBusName.selectedPatient, patientEventHandler);
  }

  nextHandler(context) async {
    if (ObjectUtil.isEmpty(_patientInfo.keyId)) {
      ToastUtil.warning("请添加就诊人");
      return;
    }
    if (ObjectUtil.isEmpty(_tentativeDiagnosis)) {
      ToastUtil.warning("请填写初步诊断信息");
      return;
    }
    if (ObjectUtil.isEmpty(_hospitalInfo.orgId)) {
      ToastUtil.warning("请选择检查医院");
      return;
    }
    if (_examineItems.length == 0) {
      ToastUtil.warning("请添加检查项目");
      return;
    }

    var itemIDS = _examineItems.map((e) => e.keyId);
    FLog("SSDD--$itemIDS");

    var params = Map<String, dynamic>()
      ..["orderSource"] = 1
      ..["doctorID"] = _userInfo.keyID ?? ""
      ..["doctorName"] = _userInfo.doctorName ?? ""
      ..["hospitalID"] = _hospitalInfo.orgId ?? ""
      ..["itemIDList"] = itemIDS.map((e) => e).toList()
      ..["patientID"] = _patientInfo.keyId ?? ""
      ..["patientIdNumber"] = _patientInfo.idCard ?? ""
      ..["patientName"] = _patientInfo.patientName ?? ""
      ..["patientPhone"] = _patientInfo.phone ?? ""
      ..["patientSex"] = _patientInfo.sex ?? ""
      ..["patientAge"] = DateUtil.returnAgeByBirthday(
          DateUtil.getDateTime(_patientInfo.birthDay))
      ..["personID"] = ""
      ..["personName"] = ""
      ..["receptTypeID"] = 0 // 1为执业医院 0直接开单 1会诊开单
      ..["orgID"] = _userInfo.orgID ?? "" // 存医生的诊所ID
      ..["ownClinic"] = 2
      ..["tentativeDiagnosis"] = _tentativeDiagnosis
      ..["note"] = _note;
    var result = await DoctorExamineHttp.offlineCreateExamineOrder(params);
    if (result.isSuccess) {
      ToastUtil.success("创建检查单成功");
      Routers.pop(context);
    }
  }

  deleteExamineItem(e) {
    FLog("删除------" + json.encode(e));
    _examineItems.remove(e);
    examineItemsSubject.add(_examineItems);
  }

  int getSumPrice() {
    int sum = 0;
    _examineItems.forEach((element) {
      sum += element.personPay;
    });

    return sum;
  }
}
